package com.sfzd5.exam.helplibrary.exam;

import com.google.gson.Gson;
import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.*;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.sfzd5.exam.helplibrary.exam.answersheet.*;
import org.apache.commons.io.FileUtils;

import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 单位 pt (point，磅) 是一个物理长度单位，指的是72分之一英寸，同时1英寸=25.4mm，也就是说1PT=0.0254mm
 */
public class PdfHelper {

    Document document;
    PdfWriter writer;

    public PdfHelper(File pdfFile) throws FileNotFoundException, DocumentException {

        //页面大小
        Rectangle rect = new Rectangle(PageSize.A4);
        //页面背景色
        rect.setBackgroundColor(BaseColor.WHITE);

        //Step 1—Create a Document.
        document = new Document(rect);
        FileOutputStream fos = new FileOutputStream(pdfFile);
        //Step 2—Get a PdfWriter instance.
        writer = PdfWriter.getInstance(document, fos);

        //页边空白
        document.setMargins(0,0,0,0);

        //Step 3—Open the Document.
        document.open();
    }

    public void addPages(ExamInof examInof, long taskId, int stuId) {

        int pageId = 0;
        do {

            MakePage makePage = null;
            PdfContentByte pdfContentByte = null;
            PdfTemplate template = null;

            //新建一页
            document.newPage();
            writer.setPageEmpty(false);

            // 初始化图形操作句柄
            Rectangle pageSize = document.getPageSize();
            float width = pageSize.getWidth();
            float height = pageSize.getHeight();
            pdfContentByte = writer.getDirectContent();
            template = pdfContentByte.createTemplate(width, height);   //绘制图形模板
            // 关键是使用AsianFontMapper替代DefaultFontMapper
            AsianFontMapper mapper = new AsianFontMapper("STSong-Light", "UniGB-UCS2-H");

            Graphics2D g2d = new PdfGraphics2D(template, width, height, mapper); //绘图接口，继承自Graphics2D
            //Graphics2D g2d = new PdfGraphics2D(template, width, height); //绘图接口，继承自Graphics2D
            Graphics2DMM graphics2DMM = new Graphics2DMM(g2d);
            makePage = new MakePage(graphics2DMM);

            if(pageId==0)
                examInof.pages = makePage.makePages(examInof);

            Page p = examInof.pages.get(pageId);

            makePage.drawPage(examInof, p, taskId, stuId);

            makePage.close();
            pdfContentByte.addTemplate(template, 0, 0);

            pageId++;
        } while (examInof.pages.size()>pageId);

    }


    public void save(){
        //Step 5—Close the Document.
        document.close();
    }


    /**
     * 主函数
     *
     * @param args
     *
     */
    public static void main(String args[]) throws FileNotFoundException, DocumentException {
        File pdfFile = new File("h.pdf");
        PdfHelper pdfHelper = new PdfHelper(pdfFile);

        ExamInof examInof = new ExamInof();
        examInof.examName = "这是一次完美的测试";
        {
            //添加选择题
            Area choiceArea = new Area();
            choiceArea.areaType = Area.AreaType.Choice;
            choiceArea.title = "一、比较与选择（1—4小题单选，每题2分；5—8小题多选，每题3分，共20分）";
            for (int i = 0; i < 8; i++)
                choiceArea.answerSheetQuestionList.add(new ChoiceAnswerSheetQuestion());
            //choiceArea.lineCount = (int) Math.ceil(choiceArea.questionList.size() / 4d);
            examInof.areaList.add(choiceArea);
        }

        {
            //添加填空题
            Area blankArea = new Area();
            blankArea.areaType = Area.AreaType.Blank;
            blankArea.title = "二、填空题（每题空2分，共20分）";
            blankArea.answerSheetQuestionList = new ArrayList<>();
            List<BlankAnswerSheetQuestion> blankQuestionList = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                BlankAnswerSheetQuestion blankQuestion = new BlankAnswerSheetQuestion();
                BlankInfo blankInfo1 = new BlankInfo();
                blankInfo1.width = 40;
                blankQuestion.getBlankInfoList().add(blankInfo1);
                blankQuestion.setBlankInfoList(blankQuestion.getBlankInfoList());
                BlankInfo blankInfo2 = new BlankInfo();
                blankInfo2.width = 40;
                blankQuestion.getBlankInfoList().add(blankInfo2);
                blankQuestion.setBlankInfoList(blankQuestion.getBlankInfoList());
                blankArea.answerSheetQuestionList.add(blankQuestion);
                blankQuestionList.add(blankQuestion);
            }
            //blankArea.lineCount = pdfHelper.getBlankLines(blankQuestionList).size();
            examInof.areaList.add(blankArea);
        }

        {
            Area expoundArea = new Area();
            expoundArea.areaType = Area.AreaType.Expound;
            expoundArea.title = "综合题（每题空2分，共20分）";
            expoundArea.answerSheetQuestionList = new ArrayList<>();
            ExpoundAnswerSheetQuestion expoundQuestion = new ExpoundAnswerSheetQuestion();
            {
                ExpoundChildQuestion ecq = new ExpoundChildQuestion();
                ecq.lineNum = 3;
                ecq.withLine = true;
                expoundQuestion.getChildQuestionList().add(ecq);
                expoundQuestion.setChildQuestionList(expoundQuestion.getChildQuestionList());
            }
            {
                ExpoundChildQuestion ecq = new ExpoundChildQuestion();
                ecq.lineNum = 3;
                ecq.withLine = true;
                expoundQuestion.getChildQuestionList().add(ecq);
                expoundQuestion.setChildQuestionList(expoundQuestion.getChildQuestionList());
            }
            {
                ExpoundChildQuestion ecq = new ExpoundChildQuestion();
                ecq.lineNum = 3;
                ecq.withLine = true;
                expoundQuestion.getChildQuestionList().add(ecq);
                expoundQuestion.setChildQuestionList(expoundQuestion.getChildQuestionList());
            }

            expoundArea.answerSheetQuestionList.add(expoundQuestion);

            examInof.areaList.add(expoundArea);
        }

        String json = new Gson().toJson(examInof);
        try {
            FileUtils.write(new File(examInof.examName+".json"), json, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        pdfHelper.addPages(examInof, 123, 12);

        pdfHelper.save();
    }
}
